<template>
  <div>
    <q-form class="dialog_card column" ref="editRef">
      <div class="row q-col-gutter-x-md dialog_form q-pa-md">
        <div class="col-12">
          <h5><q-icon name="star" color="red" />优惠券类型：</h5>
          <q-select
            outlined
            dense
            :rules="[(val) => val !== null || '请选择优惠券类型']"
            v-model="isform.coupon_type"
            option-value="id"
            option-label="name"
            :options="[
              { id: 0, name: '满减' },
              { id: 1, name: '折扣' },
              { id: 2, name: '随机' },
            ]"
            emit-value
            map-options
            style="width: 50%"
          >
            <template v-slot:no-option>
              <q-item>
                <q-item-section class="text-grey"> No results </q-item-section>
              </q-item>
            </template>
          </q-select>
        </div>

        <!-- 1折扣-->
        <div
          class="row q-col-gutter-x-md dialog_form q-pa-md"
          v-if="isform.coupon_type == 1"
        >
          <div class="col-12">
            <h5><q-icon name="star" color="red" />折扣：</h5>
            <q-input
              lazy-rules
              :rules="[
                (val) => (val && val >= 1 && val <= 9.9) || '1 =< 折扣 <= 9.9',
              ]"
              outlined
              dense
              v-model.number="isform.discount"
              type="number"
              style="width: 50%"
            />
          </div>
          <div class="col-12">
            <h5>最多折扣金额：</h5>
            <q-input
              outlined
              dense
              v-model.number="isform.discount_limit"
              type="number"
              style="width: 50%"
            />
          </div>
        </div>

        <!-- 0满减-->
        <div
          class="row q-col-gutter-x-md dialog_form q-pa-md"
          v-if="isform.coupon_type == 0"
        >
          <div class="col-12">
            <h5><q-icon name="star" color="red" />发放面额：</h5>
            <q-input
              lazy-rules
              :rules="[(val) => (val && val > 0) || '请输入发放面额']"
              outlined
              dense
              v-model.number="isform.money"
              type="number"
              style="width: 50%"
            />
          </div>

          <div class="col-12">
            <h5>
              <q-icon name="star" color="red" />满足金额可使用（0代表无限制）：
            </h5>
            <q-input
              lazy-rules
              :rules="[(val) => val !== null || '请输入满多少元使用']"
              outlined
              dense
              v-model.number="isform.at_least"
              type="number"
              style="width: 50%"
            />
          </div>
        </div>

        <!-- 2随机-->
        <div
          class="row q-col-gutter-x-md dialog_form q-pa-md"
          v-if="isform.coupon_type == 2"
        >
          <div class="col-12">
            <h5><q-icon name="star" color="red" />最低金额：</h5>
            <q-input
              lazy-rules
              :rules="[(val) => val !== null || '请输入最低金额']"
              outlined
              dense
              v-model.number="isform.min_money"
              type="number"
              style="width: 50%"
            />
          </div>

          <div class="col-12">
            <h5><q-icon name="star" color="red" />最大金额：</h5>
            <q-input
              lazy-rules
              :rules="[(val) => val !== null || '最大金额']"
              outlined
              dense
              v-model.number="isform.max_money"
              type="number"
              style="width: 50%"
            />
          </div>
        </div>

        <div class="col-12">
          <h5><q-icon name="star" color="red" />名称：</h5>
          <q-input
            lazy-rules
            :rules="[(val) => (val && val.length > 0) || '请输入名称']"
            outlined
            dense
            v-model="isform.coupon_name"
            type="text"
            clearable
            style="width: 50%"
          />
        </div>

        <div class="col-3">
          <h5><q-icon name="star" color="red" />发放量：</h5>
          <q-input
            lazy-rules
            :rules="[(val) => (val && val > 0) || '请输入大于0的发放量']"
            outlined
            dense
            v-model.number="isform.issue_count"
            type="number"
          />
        </div>

        <div class="col-12">
          <h5><q-icon name="star" color="red" />图片：</h5>
          <q-btn round>
            <q-avatar size="100px">
              <el-image
                style="width: 100px; height: 100px"
                :src="imagePath(isform.image_uri)"
                :preview-src-list="[imagePath(isform.image_uri)]"
                hide-on-click-modal
                preview-teleported
                :initial-index="1"
                fit="cover"
              />
            </q-avatar>
            <yq-uploader
              ref="yqupload"
              @uploadedAvatar="uploadedAvatar"
            ></yq-uploader>
          </q-btn>
          <div>
            <q-btn
              @click="importAvatar"
              color="primary"
              class="color-primary uploadBtn"
              style="margin: 10px 0 5px 5px"
              >点击上传</q-btn
            >
          </div>
        </div>
      </div>
    </q-form>
  </div>
</template>

<script lang="ts" setup>
import emitter from '@/components/eventbus';
import { couponAdd, couponEdit } from '@/api/goods';
import { useQuasar } from 'quasar';

interface Props {
  form: {
    coupon_id?: number;
    coupon_type?: number; //优惠券类型
    coupon_name?: string; //名称
    issue_count?: number; //发放 数量
    image_uri?: string; //图片地址
    discount?: number; //1 =< 折扣 <= 9.9 当type为1时需要添加
    discount_limit?: number; //最多折扣金额 当type为1时可选择性添加
    at_least?: number; //满多少元使用 当type为0时添加
    money?: number; //发放面额 当type为0时添加
  };
}
const props = withDefaults(defineProps<Props>(), {
  form: () => ({}),
});
const editRef = ref();
const $q = useQuasar();
const yqupload = ref();

//接收兄弟组件传递事件
emitter.on('saveData', async () => {
  console.log('saveDatasaveData');
  IsValidate();
});
//表单验证
const IsValidate = () => {
  if (editRef.value) {
    editRef.value.validate().then(async function (validate: any) {
      if (validate) {
        console.log('验证通过');
        onSubmit();
      } else {
        console.log('验证不通过');
      }
    });
  }
};
//提交数据
const onSubmit = async () => {
  if (isform.value.coupon_id) {
    const res: any = await couponEdit(isform.value);
    info(res);
    console.log('编辑111', res);
  } else {
    const res: any = await couponAdd(isform.value);
    info(res);
    console.log('新建111', res);
  }
};
//信息返回
const info = (res: any) => {
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
    emit('backList');
  }
};

//上传图片
const importAvatar = () => {
  yqupload.value.importAvatar();
  // avatarUploader.value.pickFiles();
};
const imagePath = (src: any) => {
  let path = '';
  if (src) {
    if (src.startsWith('http') || src.startsWith('https')) {
      return src;
    }
    path = `${process.env.VUE_APP_API_URL}/${src}`;
  }
  return path;
};
//上传图片回调
const uploadedAvatar = (xhr: any) => {
  console.log('图片状态回调', xhr);
  const response = JSON.parse(xhr.xhr.responseText);
  if (response.code == 200) {
    isform.value.image_uri =
      `${process.env.VUE_APP_API_URL}` + response.data.path;
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: response.msg,
    });
    console.log('图片地址:', isform.value.image_uri);
  } else {
    $q.notify({
      color: 'white',
      textColor: 'negative',
      icon: 'cancel',
      position: 'top',
      message: response.msg,
    });
  }
  console.log('上传图片完成', xhr, response);
  //清空
  yqupload.value.removeUpload();
};

const emit = defineEmits(['update:form', 'backList']);

const isform: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    console.log('props.form', props.form);
    return props.form;
  },
});

// const options: any = computed({
//   set(value: any) {
//     // emit('update:form', value);
//   },
//   get() {
//     return props.useroptions;
//   },
// });
</script>
<style scoped lang="scss"></style>
